package com.lili.collection.jdbc.plugins;

import com.lili.collection.core.domain.RunnerMsgTransfer;
import com.lili.collection.core.plugins.Plugin;
import com.lili.collection.core.runner.result.RunnerResult;
import com.lili.collection.jdbc.config.HikariPoolConfig;
import com.lili.collection.jdbc.enums.DatabaseVendor;
import com.lili.collection.jdbc.utils.JdbcUtil;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;

/**
 * JdbcInputPlugin
 *
 * @author lili
 * @date 2023/2/13 20:43
 */
@Slf4j
public abstract class JdbcPlugin<T extends HikariPoolConfig> implements Plugin<T> {

    protected T config;

    protected DatabaseVendor databaseVendor;

    protected HikariDataSource dataSource;

    @Getter
    private RunnerResult runnerResult;

    protected int executeNum;

    @Getter
    private RunnerMsgTransfer transfer;

    @Override
    public void setRunnerTransfer(RunnerMsgTransfer transfer) {
        this.transfer=transfer;
    }

    @Override
    public void setRunnerResult(RunnerResult outputRunnerResult) {
        this.runnerResult = outputRunnerResult;
    }

    @Override
    public void init(T config) {
        this.config = config;
        databaseVendor = DatabaseVendor.forUrl(this.config.getConnectionString());
        if (databaseVendor == DatabaseVendor.MYSQL) {
            Properties driverProperties = config.getDriverProperties();
            if (!driverProperties.containsKey("rewriteBatchedStatements"))
                driverProperties.setProperty("rewriteBatchedStatements", "true");
        }
        JdbcUtil.ensureJdbcDrivers();
        dataSource = JdbcUtil.createDataSource(this.config);
    }

    @Override
    public void dispose() {
        if (this.dataSource != null) JdbcUtil.closeQuietly(this.dataSource);
    }
}
